// plupload 
accessid = '';
accesskey = '';
host = '';
policyBase64 = '';
signature = '';
callbackbody = '';
filename = '';
key = '';
expire = 0;
g_object_name = '';
g_object_name_type = 'random_name';


/**
 * 设置发送url以及参数
 * @returns
 */
function send_request( url )
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        xmlhttp.open( "GET", url , false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};

/*
 * 选择生成文件名称
 * 1 使用原文件名
 * 2 随机生成文件名
 
function check_object_radio() 
{
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}
*/

/**
 * 设置签名
 * 
 */
function get_signature( url )
{
	var currDate = new Date();
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse( currDate ) / 1000; 
    if (expire < now + 3)
    {
        body = send_request( url );
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        key = obj['dir'] + '/' + currDate.getFullYear()+'-'+ parseInt( currDate.getMonth() + 1 ) +'-'+ currDate.getDate() + '/'
        return true;
    }
    return false;
};

/**
 * 随机数
 * @param len
 * @returns {String}
 */
function random_string(len) 
{
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) 
{
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

/**
 * 设置文件名称类型
 * @param filename
 * @returns {String}
 */
function calculate_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    }
    return ''
}

/**
 * 获取设置的文件名称
 * @param filename
 * @returns {String}
 */
function get_uploaded_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {
        return g_object_name
    }
}

/**
 * 设置 OSS 提交参数
 * @param up
 * @param filename
 * @param ret
 */
function set_upload_param( up, filename, ret )
{
    if (ret == false)
    {
        ret = get_signature( up.getOption( 'serverUrl' ) );
    }
    g_object_name = key;
    if (filename != '') { suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };
    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
    up.start();
}

/**
 * 用户上传图片限制
 * -----如果超过个数则默认将最后一个移除 
 * @param up
 */
function check_img_num( _obj )
{
	//当前操作对象
	var strTotalLen = $.trim( $( _obj ).parents( 'div.weui_uploader' ).find( 'div.weui_cell_ft' ).text() );
	var arrTotalNum = strTotalLen.split( '/' );
	if( arrTotalNum.length > 0 )
	{//存在图片数量限制
		var iCurNum = parseInt( arrTotalNum[0] );
		var iTotalNum = parseInt( arrTotalNum[1] );
		
		if( 1 == iTotalNum )
		{//只允许上传一张图
			$( _obj ).parent( 'div' ).prev( 'ul' ).empty();
			$( _obj ).parents( 'div.weui_uploader' ).find( 'div.weui_cell_ft' ).html( iTotalNum + '/' + iTotalNum );
		}
		else
		{
			if( iCurNum >= iTotalNum )
			{//当前上传数量大于总图片数
				$( _obj ).parent( 'div' ).prev( 'ul' ).find( 'li:last' ).remove();
				$( _obj ).parents( 'div.weui_uploader' ).find( 'div.weui_cell_ft' ).html( parseInt( iCurNum ) + '/' + iTotalNum );
			}
			else
			{
				$( _obj ).parents( 'div.weui_uploader' ).find( 'div.weui_cell_ft' ).html( parseInt( iCurNum + 1 ) + '/' + iTotalNum );
			}
		}
		
	}
}
